﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;

namespace Web.Ajax.Data
{
	public class Csv
	{
		public static string[][] ParseCsv(string csv)
		{
			if (string.IsNullOrEmpty(csv))
				return null;
			csv = csv.Replace("\r\n", "\n");
			if (!csv.EndsWith("\n")) 
				csv += "\n";

			var inquotedfield = false;
			var delimeter = ',';
			var endline = '\n';

			var rows = new List<string[]>();
			var row = new List<string>();
			var field = "";
			var justhadnewline = true;
			for (var i = 0; i < csv.Length; i++)
			{
				var newline = false;
				var cur = csv[i];
				if (inquotedfield)
				{
					if (cur == '\"')
					{
						inquotedfield = false;
						if(i==(csv.Length-1))
							newline=true;
						else
							continue;
					}
				}
				else
				{
					if (cur == '\"')
					{
						inquotedfield = true;
						continue;
					}
					if (cur == delimeter)
					{
						row.Add(field);
						field = "";
						continue;
					}
					if (cur == endline || i==(csv.Length-1))
						newline = true;
				}
				if (newline)
				{
					if (justhadnewline)
						continue;
					row.Add(field);
					rows.Add(row.ToArray());
					row = new List<string>();
					field = "";
					continue;
				}
				justhadnewline = false;
				field += cur;
			}
			return rows.ToArray();
		}

		public static DataTable ToDataTable(string[][] rows)
		{
			if (rows == null)
				return null;
			var dt=new DataTable();
			if (rows.Length == 0)
				return dt;
			var headings = rows[0];
			foreach(var h in headings)
				dt.Columns.Add(h, typeof(string));
			if (rows.Length > 1)
			{
				for (var i = 1; i < rows.Length; i++)
				{
					var row = rows[i];

					dt.Rows.Add(row);
				}
			}
			return dt;
		}

		public static DataTable ToDataTable(string csv)
		{
			return ToDataTable(ParseCsv(csv));
		}
	}
}
